package com.yxy.f_music_server.utils;

import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.yxy.f_music_server.exception.FileUploadException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;


//交给IOC容器管理
@Component
@Slf4j
public class QiniuOSSUtil {

    private static final String ACCESS_KEY = "kGJ9iYaFwv4IutttHwUZdE9f1xLglV7FdiuFehQA";
    private static final String ACCESS_SECRET_KEY = "9ojCaziL5cCvtxZFcq3lkYMn9zThnw_B4Cd8aStb";
    private static final String BUCKET = "pear-cos-2";
    private static final String DOMAIN = "http://cdn2.ymvpear.icu/f_music/";
    private static final String MUSIC_SUFFIX = "mp3";
    private static final String APK_SUFFIX = "apk";

    /**
     * 上传文件到七牛云对象存储
     * @param file
     * @param fileName
     * @return
     */
    private static boolean uploadFile(MultipartFile file, String fileName){
        // 构造一个带指定Region对象的配置类
        // 最开始配置的是自动获取区域Region.autoRegion() 报了java.net.UnknownHostException: upload-z2.qiniup.com on错误
        // 后面确认存储区域后取消自动获取，改为对应的区域region2()
        /*
          解决出处：https://www.cnblogs.com/liftsail/p/16944399.html
          存储区域
          华东机房(region0): up.qiniup.com 或 upload.qiniup.com
          华北机房(region1): up-z1.qiniup.com 或 upload-z1.qiniup.com
          华南机房(region2): up-z2.qiniup.com 或 upload-z2.qiniup.com
          北美机房(regionNa0): up-na0.qiniup.com 或 upload-na0.qiniup.com
          新加坡机房(regionAs0): up-as0.qiniup.com 或 upload-as0.qiniup.com
          雾存储华东一区(regionFogCnEast1): up-fog-cn-east-1.qiniup.com 或 upload-fog-cn-east-1.qiniup.com
         */
        // 初始化配置类，指定区域
        Configuration cfg = new Configuration(Region.region2());
        // 创建上传管理器
        UploadManager uploadManager = new UploadManager(cfg);
        // 默认不指定key的情况下会以文件内容的hash值作为文件名
        try {
            // 获取文件名 （包括了文件后缀）
            String _fileName = file.getOriginalFilename();
            // 后缀名
            String suffix = _fileName.substring(_fileName.lastIndexOf(".") + 1);
            // 文件夹名
            String folderName = null;
            if(suffix.equals(APK_SUFFIX)){
                folderName = APK_SUFFIX;
            }else if (suffix.equals(MUSIC_SUFFIX)){
                folderName = MUSIC_SUFFIX;
            }
            byte[] bytes = file.getBytes();
            Auth auth = Auth.create(ACCESS_KEY, ACCESS_SECRET_KEY);
            String upToken = auth.uploadToken(BUCKET);
            Response response = uploadManager.put(bytes, "f_music/" + folderName + "/" + fileName, upToken);
            // 打印日志
            log.info("上传结果：{}", response.bodyString());
            return true;
        } catch (IOException e) {
            throw new FileUploadException(e.getMessage());
        }
    }

    /**
     * 上传文件
     * @param file
     * @return
     */
    public static String uploadToQiniu(MultipartFile file){
        // 获取文件名 （包括了文件后缀）
        String fileName = file.getOriginalFilename();
        // 后缀名
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        // 文件夹名
        String folderName = null;
        if(suffix.equals(APK_SUFFIX)){
            folderName = APK_SUFFIX;
        }else if (suffix.equals(MUSIC_SUFFIX)){
            folderName = MUSIC_SUFFIX;
        }
        System.out.println(suffix);
        System.out.println(folderName);
        // 文件是否上传成功
        boolean flag = uploadFile(file, fileName);
        return flag ? DOMAIN + folderName + "/" + fileName : null;
    }

    /**
     * 上传文件（包含上传的音乐名）
     * @param file
     * @param songName
     * @return
     */
    public static String uploadToQiniu(MultipartFile file, String songName){
        // 获取文件名 （包括了文件后缀）
        String fileName = file.getOriginalFilename();
        // 后缀名
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        // 文件夹名
        String folderName = null;
        if(suffix.equals(APK_SUFFIX)){
            folderName = APK_SUFFIX;
        }else if (suffix.equals(MUSIC_SUFFIX)){
            folderName = MUSIC_SUFFIX;
        }
        // 文件是否上传成功
        boolean flag = uploadFile(file, songName + ".mp3");
        return flag ? DOMAIN + folderName + "/" + songName + ".mp3" : null;
    }

    /**
     * 删除文件
     * @param filename 要删除的七牛云中存储的文件名
     */
    public static void deleteFileFromQiniu(String filename){
        // 初始化一个配置类，指定区域
        Configuration configuration = new Configuration(Region.region2());
        // 创建上传管理器
        UploadManager uploadManager = new UploadManager(configuration);
        try{
            Auth auth = Auth.create(ACCESS_KEY, ACCESS_SECRET_KEY);
            BucketManager bucketManager = new BucketManager(auth, configuration);
            // 删除文件
            Response response = bucketManager.delete(BUCKET, filename);
            log.info("文件删除成功");
        }catch (IOException e){
            log.error("文件删除失败：{}", e.getMessage());
            throw new FileUploadException("operation error" + e.getMessage());
        }
    }
}
